package com.miku.project.controller;
import java.util.Date;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.miku.mikuapicommon.model.entity.User;
import com.miku.project.annotation.AuthCheck;
import com.miku.project.common.*;
import com.miku.project.config.EmailConfig;
import com.miku.project.exception.BusinessException;
import com.miku.project.model.dto.user.*;
import com.miku.project.model.enums.UserAccountStatusEnum;
import com.miku.project.model.vo.UserVO;
import com.miku.project.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.miku.project.constant.EmailConstant.*;
import static com.miku.project.constant.UserConstant.ADMIN_ROLE;
import static com.miku.project.utils.EmailUtil.buildEmailContent;

/**
 * 用户接口
 *
 * @author <a href="https://gitee.com/deng-taotao-eee">miku</a>
 * @from <a href=""></a>
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private EmailConfig emailConfig;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }


    @PostMapping("/email/login")
    @ApiOperation("用户邮箱登录")
    public BaseResponse<UserVO> emailLogin(@RequestBody UserEmailLoginRequest userEmailLoginRequest, HttpServletRequest request) {
        if (userEmailLoginRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
       UserVO  userVO=userService.userEmailLogin(userEmailLoginRequest, request);
        // 从redis中删除CAPTCHA_CACHE_KEY+userEmailLoginRequest.getEmailAccount()对应的键
        redisTemplate.delete(CAPTCHA_CACHE_KEY + userEmailLoginRequest.getEmailAccount());
        return ResultUtils.success(userVO);
    }

    /**
     * 用户电子邮箱注册
     *
     * @return
     */
    @ApiOperation("用户邮箱注册")
    @PostMapping("/email/register")
    public BaseResponse<Long> userEmailRegister(@RequestBody UserEmailRegisterRequest userEmailRegisterRequest) {
        // 判断userEmailRegisterRequest是否为空
        if (userEmailRegisterRequest == null) {
        // 抛出业务异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long result = userService.userEmilRegister(userEmailRegisterRequest);
         // 从redis中删除CAPTCHA_CACHE_KEY+userEmailRegisterRequest.getEmailAccount()对应的键
        redisTemplate.delete(CAPTCHA_CACHE_KEY + userEmailRegisterRequest.getEmailAccount());
        return ResultUtils.success(result);
    }

    /**
     * 获取验证码
     * @param emailAccount
     * @return
     */
    @ApiOperation("获取邮箱验证码")
    @GetMapping("/getCaptcha")
    public BaseResponse<String> getCaptcha(String emailAccount){
        //1.校验参数
        if (StringUtils.isAnyBlank(emailAccount)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        if (!emailAccount.matches(emailPattern)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"邮箱格式错误");
        }
        //生成验证码
        String captcha = RandomUtil.randomNumbers(6);
        try {
            //2.发送验证码
            sendEmail(emailAccount,captcha);
            String key = CAPTCHA_CACHE_KEY + emailAccount;
            //存入redis，验证码5分钟过期
            redisTemplate.opsForValue().set(key,captcha,5, TimeUnit.MINUTES);
            return ResultUtils.success(captcha);
        } catch (Exception e) {
            log.error("发送邮件失败",e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"发送邮件失败");
        }
    }

    /**
     * 用户绑定电子邮箱
     * @param userEmailBindRequest
     * @return
     */
    @ApiOperation("用户邮箱绑定")
    @PostMapping("/bind/login")
    public BaseResponse<UserVO> userBindEmail(@RequestBody UserEmailBindRequest userEmailBindRequest,HttpServletRequest request) {
        if (userEmailBindRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO=userService.userBindEmail(userEmailBindRequest,request);
        return ResultUtils.success(userVO);
    }

    /**
     * 用户解绑电子邮箱
     * @param userEmailBindRequest
     * @param request
     * @return
     */
    @ApiOperation("用户解绑电子邮箱")
    @PostMapping("/unbindEmail")
    public BaseResponse<UserVO> userUnBindEmail(@RequestBody UserEmailBindRequest userEmailBindRequest,HttpServletRequest request) {
        if (userEmailBindRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO=userService.userUnBindEmail(userEmailBindRequest,request);
        redisTemplate.delete(CAPTCHA_CACHE_KEY + userEmailBindRequest.getEmailAccount());
        return ResultUtils.success(userVO);
    }

    /**
     * 发送和验证码
     * @param emailAccount
     * @param captcha
     */
    private void sendEmail(String emailAccount, String captcha) {
        MimeMessage message=mailSender.createMimeMessage();
        //邮箱发送内容组成
        try {
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setSubject(EMAIL_SUBJECT);
            helper.setText(buildEmailContent(emailAccount,captcha),true);
            helper.setTo(emailAccount);
            helper.setFrom(EMAIL_TITLE+"<"+emailConfig.getEmailFrom()+">");
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"发送邮件失败");
        }
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("用户注销接口")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation("获取当前登录用户")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
        UserVO user = userService.getLoginUser(request);
        return ResultUtils.success(user);
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建用户")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        userService.validUser(user,true);
        boolean result = userService.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除用户")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新用户")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<UserVO> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //只有管理员才能操作
        boolean adminOperation = ObjectUtils.isNotEmpty(userUpdateRequest.getBalance())
                || StringUtils.isNoneBlank(userUpdateRequest.getUserRole())
                || StringUtils.isNoneBlank(userUpdateRequest.getUserPassword());
        //校验是否登录
        UserVO loginUser = userService.getLoginUser(request);
        if (adminOperation && !loginUser.getUserRole().equals(ADMIN_ROLE)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        if (!loginUser.getUserRole().equals(ADMIN_ROLE) && !userUpdateRequest.getId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有本人或管理员可以修改");
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        // 参数校验
        userService.validUser(user, false);

        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userLambdaUpdateWrapper.eq(User::getId, user.getId());

        boolean result = userService.update(user, userLambdaUpdateWrapper);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新失败");
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userService.getById(user.getId()), userVO);
        return ResultUtils.success(userVO);
    }

    /**
     * 根据 id 获取用户
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @ApiOperation("获取用户详细信息")
    public BaseResponse<UserVO> getUserById(int id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }

    /**
     * 获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    public BaseResponse<List<UserVO>> listUser(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User userQuery = new User();
        BeanUtils.copyProperties(userQueryRequest, userQuery);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        List<User> userList = userService.list(queryWrapper);
        List<UserVO> userVOList = userList.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(userVOList);
    }

    /**
     * 分页获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @ApiOperation("分页获取用户列表")
    public BaseResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        //校验参数
        if (userQueryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        Integer gender = userQueryRequest.getGender();
        String userRole = userQueryRequest.getUserRole();
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        //设置默认的分页参数
        if (current == 0){
            current = 1;
        }
        if (pageSize == 0){
            pageSize = 10;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(userName),"userName", userName)
                .eq(StringUtils.isNotBlank(userAccount),"userAccount", userAccount)
                .eq(gender != null, "gender", gender)
                .eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        Page<User> userPage =userService.page(new Page<>(current, pageSize), queryWrapper);
        Page<UserVO> userVOPage=new PageDTO<>(userPage.getCurrent(),userPage.getSize(),userPage.getTotal());
        List<UserVO> userVOList=userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        userVOPage.setRecords(userVOList);

        return ResultUtils.success(userVOPage);

    }

    // endregion

    /**
     * 更新凭证
     * @param request
     * @return
     */
    @PostMapping("/update/voucher")
    @ApiOperation("更新凭证")
    public BaseResponse<UserVO> updateVoucher(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(loginUser, user);
        UserVO userVO = userService.updateVoucher(user);
        return ResultUtils.success(userVO);
    }

    /**
     * 根据邀请码获取用户信息
     * @param inviteCode
     * @return
     */
    @ApiOperation("根据邀请码获取用户信息")
    @PostMapping("/get/invitationCode")
    public BaseResponse<UserVO> getUserByInviteCode(String inviteCode) {
        if (StringUtils.isBlank(inviteCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //根据邀请码查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getInvitationCode, inviteCode);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        return ResultUtils.success(userVO);
    }


    /**
     * 禁号
     * @param idRequest
     * @return
     */
    @PostMapping("/ban")
    @AuthCheck(mustRole = ADMIN_ROLE)
    @ApiOperation("封禁用户")
    public BaseResponse<Boolean> BanUser(@RequestBody IdRequest idRequest){
        if (ObjectUtils.anyNull(idRequest, idRequest.getId())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long id = idRequest.getId();
        //查询用户
        User user = userService.getById(id);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //修改用户状态
        user.setStatus(UserAccountStatusEnum.BAN.getValue());
        boolean result = userService.updateById(user);
        return ResultUtils.success(result);
    }

    /**
     * 解封用户
     * @param idRequest
     * @return
     */
    @AuthCheck(mustRole = ADMIN_ROLE)
    @PostMapping("/normal")
    @ApiOperation("解封用户")
    public BaseResponse<Boolean> UnBanUser(@RequestBody IdRequest idRequest){

        if (ObjectUtils.anyNull(idRequest, idRequest.getId())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long id = idRequest.getId();
        //查询用户
        User user = userService.getById(id);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //修改用户状态
        user.setStatus(UserAccountStatusEnum.NORMAL.getValue());
        boolean result = userService.updateById(user);

        return ResultUtils.success(result);
    }



}
